package xin.petstore.framework.orm.mybatis.paginator.support;

import xin.petstore.framework.orm.mybatis.paginator.dialect.Dialect;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.transaction.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SQLHelp {
    private static Logger logger = LoggerFactory.getLogger(SQLHelp.class);

    public static int getCount(MappedStatement mappedStatement, Transaction transaction, Object parameterObject, BoundSql boundSql, Dialect dialect)
            throws SQLException {
        String count_sql = dialect.getCountSQL();
        logger.debug("Total count SQL [{}] ", count_sql);
        logger.debug("Total count Parameters: {} ", parameterObject);

        Connection connection = transaction.getConnection();
        PreparedStatement countStmt = connection.prepareStatement(count_sql);
        DefaultParameterHandler handler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);
        handler.setParameters(countStmt);

        ResultSet rs = countStmt.executeQuery();
        int count = 0;
        if (rs.next()) {
            count = rs.getInt(1);
        }
        logger.debug("Total count: {}", Integer.valueOf(count));
        return count;
    }
}
